import { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Decimal } from "decimal.js";
import { Address } from "@/types/address";
import { orderService } from "@/service/orderService";
import { toast } from "sonner";
import { CartItemsByMerchant } from "@/types/cart";
import { formatAddress } from "@/utils/address";
import Loading from "../misc/Loading";
import { payService } from "@/service/payService";


export default function OrderConfirm() {
  const location = useLocation();// 获取购物车页面传递的参数
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [addresses, setAddresses] = useState<Address[]>([]);
  const [selectedAddressId, setSelectedAddressId] = useState<number | null>(null);
  const [merchantGroups, setMerchantGroups] = useState<CartItemsByMerchant[]>([]);
  const [totalPrice, setTotalPrice] = useState<string | null>(null);
  const [showSuccessDialog, setShowSuccessDialog] = useState(false);

  // 从购物车页面传递过来的商品
  const skuIds = (location.state?.skuIds || []) as number[];

  useEffect(() => {
    if (skuIds.length === 0) {
      navigate("/mall/cart");
      return;
    }

    const fetchOrderConfirmData = async () => {
      setLoading(true);

      const confirmData = await orderService.confirmOrderView(skuIds);
      if (!confirmData) {
        toast.error("获取订单确认数据失败，请稍后重试");
        setLoading(false);
        navigate("/mall/cart");
        return;
      }

      if (confirmData.groups.length == 0) {
        toast.error("找不到商品，请稍后重试");
        setLoading(false);
        navigate("/mall/cart");
        return;
      }

      // 设置地址列表和默认选中地址
      setAddresses(confirmData.addresses);
      const defaultAddress = confirmData.addresses.find(addr => addr.isDefault);
      setSelectedAddressId(defaultAddress?.id || confirmData.addresses[0]?.id || null);
      setTotalPrice(confirmData.totalPrice);

      // 按商家分组商品
      setMerchantGroups(confirmData.groups);
      setLoading(false);
    };
    fetchOrderConfirmData();

  }, [skuIds]);



  // 更新收货地址
  const handleUpdateAddress = async (addressId: number) => {
    setSelectedAddressId(addressId);
    // 发送更新地址请求
  };


  // 提交订单
  const handleSubmitOrder = async () => {
    if (!selectedAddressId) {
      toast.error("请选择收货地址");
      return;
    }

    setLoading(true);

    const orderData = {
      addressId: selectedAddressId,
      skuIds: merchantGroups.flatMap(group =>
        group.items.map(item => (item.skuId))
      ),
      note: "尽快发货"
    };

    const orderId = await orderService.submitOrder(orderData);
    if (!orderId) {
      toast.error("提交订单失败，请稍后重试");
      setLoading(false);
      navigate("/mall/cart");
      return;
    }
    const alipayHtml = await payService.requestPayment(orderId);
    if (!alipayHtml) {
      toast.error("支付请求失败，请稍后重试");
      setLoading(false);
      navigate("/mall/cart");
      return;
    }
    const newTab = window.open("", "_blank");
    if (newTab) {
      newTab.document.writeln(alipayHtml);
      newTab.document.close();
    }
    navigate("/mall/orders");
    // setShowSuccessDialog(true);
    setLoading(false);
    return;

  };




  if (loading) {
    return <Loading />;
  }

  return (
    <div className="max-w-6xl mx-auto">
      <h1 className="text-2xl font-bold mb-6">订单确认</h1>

      {/* 收货地址 */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle className="flex items-center">
            <span className="mr-2">收货地址</span>
            <Button variant="outline" size="sm" className="ml-auto">
              管理地址
            </Button>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <RadioGroup
            value={selectedAddressId?.toString()}
            onValueChange={(value) => handleUpdateAddress(parseInt(value))}
          >
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {addresses.map(address => (
                <div
                  key={address.id}
                  className={`border rounded-lg p-4 cursor-pointer transition-colors ${selectedAddressId === address.id ? 'border-primary bg-primary/5' : 'border-border'
                    }`}
                >
                  <div className="flex items-start">
                    <RadioGroupItem
                      value={address.id.toString()}
                      id={`address-${address.id}`}
                      className="mt-1 mr-2"
                    />
                    <div className="flex-1">
                      <div className="flex items-center mb-1">
                        <span className="font-medium">{address.receiverName}</span>
                        <span className="mx-2 text-muted-foreground">{address.receiverPhone}</span>
                        {address.isDefault && (
                          <span className="text-xs px-2 py-0.5 bg-primary/10 text-primary rounded">默认</span>
                        )}
                      </div>
                      <p className="text-sm text-muted-foreground">{formatAddress(address)}</p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </RadioGroup>
        </CardContent>
      </Card>

      {/* 商品列表 */}
      <div className="space-y-6 mb-6">
        {merchantGroups.map((group) => (
          <Card key={group.merchantId}>
            <CardHeader className="pb-2">
              <div className="flex items-center">
                <img src={group.merchantLogo} className="w-10 h-10 rounded-full mr-2" />
                {/* <div className="w-6 h-6 bg-gray-200 rounded-full mr-2"></div> */}
                <CardTitle className="text-base">{group.merchantName}</CardTitle>
              </div>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {group.items.map(item => (
                  <div key={item.skuId} className="flex items-center py-3 border-b last:border-0">
                    <img src={item.imageUrl} alt="商品图片" className="h-16 w-16 items-center justify-center rounded" />
                    <div className="flex-1 ml-4">
                      <h3 className="font-medium">{item.spuName}</h3>
                      <p className="text-sm text-muted-foreground">规格: {item.specs}</p>
                    </div>

                    <div className="flex-1 text-sm text-muted-foreground mr-4">
                      x{item.quantity}
                    </div>

                    <div className="w-20 text-right font-medium">
                      ¥{new Decimal(item.price).toFixed(2)}
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* 订单摘要 */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>订单摘要</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-2">
            <div className="flex justify-between">
              <span>商品总价</span>
              <span>¥{totalPrice}</span>
            </div>
            <div className="flex justify-between">
              <span>运费</span>
              <span>¥0.00</span>
            </div>
            <div className="border-t pt-2 mt-2 font-bold flex justify-between">
              <span>实付金额</span>
              <span className="text-primary text-xl">¥{totalPrice}</span>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 提交订单 */}
      <div className="flex justify-end mb-10">
        <Button
          size="lg"
          onClick={handleSubmitOrder}
          disabled={loading}
          className="px-8"
        >
          {loading ? "处理中..." : "提交订单"}
        </Button>

      </div>
      {/* <Dialog open={showSuccessDialog} onOpenChange={setShowSuccessDialog}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>提交成功</DialogTitle>
          </DialogHeader>
          <DialogDescription className="text-center py-4">
            支付页面已在新标签页中打开
          </DialogDescription>
          <DialogFooter className="sm:justify-center">

            <Button onClick={() => {setShowSuccessDialog(false); window.location.reload(); }}>
              支付成功，点击刷新
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog> */}
    </div>
  );
}